/**
 * RenweiWu
 * PlatformAnalyzesService.java
 * 2017年8月31日
 * PlatformAnalyzesService
 * TODO
 * 
 */
package com.etrans.web.gps.business.report.service;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.etrans.web.gps.business.report.domain.PlatformAnalyseCarType;
import com.etrans.web.gps.business.report.domain.PlatformAnalyzes;
import com.etrans.web.gps.business.report.domain.Vocational;
import com.etrans.web.gps.business.system.service.CommonService;
import com.etrans.web.gps.common.MGTemplete;
import com.etrans.web.gps.util.DateUtil;
import com.mongodb.QueryOperators;

/**
 * @Description:TODO
 * @author RenweiWu
 * @date 2017年8月31日
 * @ClassName:  PlatformAnalyzesService  
 * @param:   
 */
@Service
public class PlatformAnalyzesService {
	
	private static final SimpleDateFormat SDF = new SimpleDateFormat("yyMMdd");
	@Autowired
	public CommonService commonService;

	public Map<String,Object> queryAnalyzes(String veidoo,String analyse_date,int areaId,String gnss_centerid) throws ParseException{
		Map<String,Object> resultMap = new HashMap<String,Object>();
		Set<String> idList = new HashSet<String>();
		HashMap<String,Object> whereMap = new HashMap<String,Object>();
		String id=null;
		List<Document> reslist = null;
		HashMap<String,Object> whereMapparam = new HashMap<String,Object>();
		if(analyse_date!=null&&!"".equals(analyse_date)){
			if("day".equals(veidoo)){
				if(StringUtils.isBlank(gnss_centerid)){
					HashMap<String, Object> param = new HashMap<String, Object>();
					param.put("FullID", String.format("%08d",areaId));
					List<HashMap<String,Object>> list = commonService.selectqueryplatformbyAreaID(param);
					if(list != null && list.size() > 0){
						for (HashMap<String, Object> hashMap : list) {
							id = SDF.format(DateUtil.getStrToDate(analyse_date))+":"+hashMap.get("gnss_centerid");
							idList.add(id);
						}
					}
				}else{
					id = SDF.format(DateUtil.getStrToDate(analyse_date))+":"+gnss_centerid;
					idList.add(id);
				}
				//System.out.println(idList.toString());
				whereMapparam.put(QueryOperators.IN,idList);
				whereMap.put("_id", whereMapparam);
				reslist = MGTemplete.findDocuments("egov", "platform_swap",whereMap);
			}else if ("week".equals(veidoo)) {
				int year = Integer.parseInt((analyse_date).split("-")[0]);
				int week = Integer.parseInt((analyse_date).split("-")[1]);
				Map<String,Object> map =DateUtil.getYearAndWeekByDate(year, week);
				if(gnss_centerid==null||"".equals(gnss_centerid)){
					HashMap<String, Object> param = new HashMap<String, Object>();
					param.put("FullID", String.format("%08d",areaId));
					List<HashMap<String,Object>> list = commonService.selectqueryplatformbyAreaID(param);
					if(list != null && list.size() > 0){
						for (HashMap<String, Object> hashMap : list) {
							id = SDF.format(DateUtil.getStrToDate((String)map.get("Monday")))+":"+hashMap.get("gnss_centerid");
							idList.add(id);
						}
					}
				}else{
					id = SDF.format(DateUtil.getStrToDate((String)map.get("Monday")))+":"+gnss_centerid;
					idList.add(id);
				}		
				whereMapparam.put(QueryOperators.IN,idList);
				whereMap.put("_id", whereMapparam);
				reslist = MGTemplete.findDocuments("egov", "platform_swap_week",whereMap);
			}else if ("month".equals(veidoo)) {
				if(gnss_centerid==null||"".equals(gnss_centerid)){
					HashMap<String, Object> param = new HashMap<String, Object>();
					param.put("FullID", String.format("%08d",areaId));
					List<HashMap<String,Object>> list = commonService.selectqueryplatformbyAreaID(param);
					if(list != null && list.size() > 0){
						for (HashMap<String, Object> hashMap : list) {
							id = SDF.format(DateUtil.getStrToDate(analyse_date+"-01"))+":"+hashMap.get("gnss_centerid");
							idList.add(id);
						}
					}
				}else{
					id = SDF.format(DateUtil.getStrToDate(analyse_date+"-01"))+":"+gnss_centerid;
					idList.add(id);
				}
				whereMapparam.put(QueryOperators.IN,idList);
				whereMap.put("_id", whereMapparam);
				reslist = MGTemplete.findDocuments("egov", "platform_swap_month",whereMap);
			}
		}	
		List<PlatformAnalyzes> listAnalyzes=null;
		List<PlatformAnalyseCarType> clist = null;
		PlatformAnalyseCarType  catType = null;
		if(reslist!=null){
			Document trade_obj =null;
			PlatformAnalyzes  Analyzes;
			String json;
			clist = new ArrayList<PlatformAnalyseCarType>();
			catType = new PlatformAnalyseCarType();
			catType.setDangerCar("车辆总数|入网数(率)|上线数(率)");
			catType.setRegularBus("车辆总数|入网数(率)|上线数(率)");
			catType.setTouringCar("车辆总数|入网数(率)|上线数(率)");
			clist.add(catType);
			listAnalyzes = new ArrayList<PlatformAnalyzes>();
			for (Document document : reslist) {
				trade_obj = (Document)document.get("trade_obj");
				PlatformAnalyseCarType carType = getVocational(trade_obj,(String)document.get("platform_name"));
				
				clist.add(carType);
				json = JSONObject.toJSONString(document);
				Analyzes = JSONObject.toJavaObject(JSONObject.parseObject(json),PlatformAnalyzes.class);
				listAnalyzes.add(Analyzes);
			}
			Collections.sort(listAnalyzes,Collections.reverseOrder(new Comparetores()));
			int i=1;
			for (PlatformAnalyzes vo : listAnalyzes) {
					vo.setRanking(i);
					i++;
			}
		}
		resultMap.put("listAnalyzes", listAnalyzes);
		resultMap.put("list",clist);
		return resultMap;
	}
	private PlatformAnalyseCarType getVocational(Document d,String platformName){
		DecimalFormat DFS = new DecimalFormat("#.00");
		Document document;
		String json;
		Vocational vo;
		PlatformAnalyseCarType carType = new PlatformAnalyseCarType(); 
		String str = null;
		carType.setPlatformName(platformName);
		
		document =(Document)d.get("1");
		json = JSONObject.toJSONString(document);
		vo = JSONObject.toJavaObject(JSONObject.parseObject(json),Vocational.class);
/*		map.put("regularBus",vo);*/	
		str =  vo.getVehicle_count()+"|"+vo.getVehicle_access_count()+"("+(vo.getVehicle_access_rate()>1?DFS.format(vo.getVehicle_access_rate()):vo.getVehicle_access_rate()==0.0?0:vo.getVehicle_access_rate())+"%)|"+vo.getVehicle_online_count()+"("+(vo.getVehicle_online_rate()>1?DFS.format(vo.getVehicle_online_rate()):vo.getVehicle_online_rate()==0.0?0:vo.getVehicle_online_rate())+"%)";
		carType.setRegularBus(str);
		
		document =(Document)d.get("2");
		json = JSONObject.toJSONString(document);
		vo = JSONObject.toJavaObject(JSONObject.parseObject(json),Vocational.class);
/*		map.put("touringCar",vo);*/	
		str =  vo.getVehicle_count()+"|"+vo.getVehicle_access_count()+"("+(vo.getVehicle_access_rate()>1?DFS.format(vo.getVehicle_access_rate()):vo.getVehicle_access_rate()==0.0?0:vo.getVehicle_access_rate())+"%)|"+vo.getVehicle_online_count()+"("+(vo.getVehicle_online_rate()>1?DFS.format(vo.getVehicle_online_rate()):vo.getVehicle_online_rate()==0.0?0:vo.getVehicle_online_rate())+"%)";
		carType.setTouringCar(str);
		
		document =(Document)d.get("3");
		json = JSONObject.toJSONString(document);
		vo = JSONObject.toJavaObject(JSONObject.parseObject(json),Vocational.class);
/*		map.put("dangerCar",vo);*/
		str =  vo.getVehicle_count()+"|"+vo.getVehicle_access_count()+"("+(vo.getVehicle_access_rate()>1?DFS.format(vo.getVehicle_access_rate()):vo.getVehicle_access_rate()==0.0?0:vo.getVehicle_access_rate())+"%)|"+vo.getVehicle_online_count()+"("+(vo.getVehicle_online_rate()>1?DFS.format(vo.getVehicle_online_rate()):vo.getVehicle_online_rate()==0.0?0:vo.getVehicle_online_rate())+"%)";
		carType.setDangerCar(str);
		
		return carType;
	}
	
	public List<PlatformAnalyzes> getShadowRegion(int areaId,String gnss_centerid,String analyse_date,String veidoo){
		Set<String> idList = new HashSet<String>();
		HashMap<String,Object> whereMap = new HashMap<String,Object>();
		String id=null;
		List<Document> reslist = null;
		HashMap<String,Object> whereMapparam = new HashMap<String,Object>();
		if(analyse_date!=null&&!"".equals(analyse_date)){
			if("day".equals(veidoo)){
				if(gnss_centerid!=null&&!"".equals(gnss_centerid)){
					try {
						id = SDF.format(DateUtil.getStrToDate(analyse_date))+":"+gnss_centerid;
					} catch (ParseException e) {
						e.printStackTrace();
					}
				}
				whereMap.put("_id", id);
				reslist = MGTemplete.findDocuments("egov", "platform_swap",whereMap);
			}else if ("week".equals(veidoo)) {
				int year = Integer.parseInt((analyse_date).split("-")[0]);
				int week = Integer.parseInt((analyse_date).split("-")[1]);
				Map<String,Object> map =DateUtil.getYearAndWeekByDate(year, week);
				if(gnss_centerid!=null&&!"".equals(gnss_centerid)){
					List<String> time = DateUtil.getDates((String)map.get("Monday"),(String)map.get("Sunday"));
					for (String string : time) {
						try {
							id = SDF.format(DateUtil.getStrToDate(string))+":"+gnss_centerid;
						} catch (ParseException e) {
							e.printStackTrace();
						}
						idList.add(id);
					}
				}		
				whereMapparam.put(QueryOperators.IN,idList);
				whereMap.put("_id", whereMapparam);
				reslist = MGTemplete.findDocuments("egov", "platform_swap",whereMap);
			}else if ("month".equals(veidoo)) {
				if(gnss_centerid!=null&&!"".equals(gnss_centerid)){
					List<String> time = DateUtil.getMonday(analyse_date);
					for (String string : time) {
						try {
							id =SDF.format(DateUtil.getStrToDate(string))+":"+gnss_centerid;
						} catch (ParseException e) {
							e.printStackTrace();
						}
						idList.add(id);
					}
				}
				whereMapparam.put(QueryOperators.IN,idList);
				whereMap.put("_id", whereMapparam);
				reslist = MGTemplete.findDocuments("egov", "platform_swap_week",whereMap);
			}
		}
		List<PlatformAnalyzes> listAnalyzes = new ArrayList<PlatformAnalyzes>();
		PlatformAnalyzes  Analyzes;
		if(reslist != null && reslist.size() > 0){
			for (Document document : reslist) {
				String json = JSONObject.toJSONString(document);
				Analyzes = JSONObject.toJavaObject(JSONObject.parseObject(json),PlatformAnalyzes.class);
				listAnalyzes.add(Analyzes);
			}
		}
		return listAnalyzes;
	}

	/**
	 * 
	 * @Description:TODO
	 * @author RenweiWu
	 * @date 2017年9月5日
	 * @ClassName:  Comparetores  
	 * @param: Comparator<T>
	 */
	public static class Comparetores implements Comparator<PlatformAnalyzes>{
		public int compare(PlatformAnalyzes analyzes1, PlatformAnalyzes analyzes2) {
	        int maxs=analyzes1.getScore()-analyzes2.getScore();
	         if(maxs==0){
	        	 int a1=(analyzes1.getTrack_normal()+analyzes1.getException_track_count())<=0?1:(analyzes1.getTrack_normal()+analyzes1.getException_track_count());
	        	 int a2=(analyzes2.getTrack_normal()+analyzes2.getException_track_count())<=0?1:(analyzes2.getTrack_normal()+analyzes2.getException_track_count());
	        	 int maxn = (int)(((double)analyzes1.getException_track_count()/a1)-((double)analyzes2.getException_track_count()/a2));
	        	 if (maxn==0) {
					return analyzes1.getScore()<=analyzes2.getScore()?-1:1;
				} else {
					return maxn;
				}
	         }else{
	 	        return maxs;
	         }
		}		
	}
}
